package io.renren.modules.bs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.bs.dao.BsExtractDetailPatientDao;
import io.renren.modules.bs.entity.BsExtractDetailPatientEntity;
import io.renren.modules.bs.entity.BsExtractDetailPatientHandleEntity;
import io.renren.modules.bs.service.BsExtractDetailPatientHandleService;
import io.renren.modules.bs.service.BsExtractDetailPatientService;
import io.renren.modules.bs.vo.ExtractDetailPatientVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("bsExtractDetailPatientService")
public class BsExtractDetailPatientServiceImpl extends ServiceImpl<BsExtractDetailPatientDao, BsExtractDetailPatientEntity> implements BsExtractDetailPatientService {

    @Autowired
    private BsExtractDetailPatientHandleService handleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BsExtractDetailPatientEntity> page = this.page(
                new Query<BsExtractDetailPatientEntity>().getPage(params),
                new QueryWrapper<BsExtractDetailPatientEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ExtractDetailPatientVo> listByDetailId(Long detailId) {
        List<ExtractDetailPatientVo> extractDetailPatientVos = this.baseMapper.listByDetailId(detailId);
        Set<Long> collect = extractDetailPatientVos.stream().map(ExtractDetailPatientVo::getExtractDetailPatientId).collect(Collectors.toSet());
        if(collect.size() > 0){
            QueryWrapper<BsExtractDetailPatientHandleEntity> handleEntityQueryWrapper = new QueryWrapper<>();
            handleEntityQueryWrapper.in("detail_patient_id", collect);
            List<BsExtractDetailPatientHandleEntity> list = this.handleService.list(handleEntityQueryWrapper);
            Map<Long, List<BsExtractDetailPatientHandleEntity>> groupBy = list.stream().collect(Collectors.groupingBy(BsExtractDetailPatientHandleEntity::getDetailPatientId));
            for (ExtractDetailPatientVo extractDetailPatientVo:extractDetailPatientVos) {
                extractDetailPatientVo.setHandleList(groupBy.get(extractDetailPatientVo.getExtractDetailPatientId()));
            }
        }
        return extractDetailPatientVos;
    }

}